package com.yulintu.parser;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yulintu.dao.BaseBodyDaoService;
import com.yulintu.dao.JsonBodyDaoService;

import java.util.List;
import java.util.Set;

/**
 * @author caomin
 * @date 2017/10/25
 * @说明 json解析body体
 */
public class JsonBodyParser<T> extends AbstractBodyParser {




    @Override
    public BaseBodyDaoService getBaseBodyDaoService(List list) {
        return new JsonBodyDaoService();
    }

    @Override
    public BaseBodyDaoService getBaseBodyDaoService() {

        return new JsonBodyDaoService();
    }

    @Override
    public AbstractBodyParser getAbstractBodyParser() {
        return new JsonBodyParser<T>();
    }

    /**
     * 根据key获取value
     * @param jsonObject
     * @param parmarterKey
     * @return
     */
    public String getValueByKey(JSONObject jsonObject,String parmarterKey){
        Set<String> keys = jsonObject.keySet();
        for (String key : keys) {
            Object obj = jsonObject.get(key);
            if (obj instanceof JSONObject) {
                String valueByKey = getValueByKey((JSONObject) obj, parmarterKey);
                if (valueByKey!=null){
                    return valueByKey;
                }
            } else if (obj instanceof JSONArray) {
                JSONArray array  =(JSONArray)obj;
                for (int i=0;i<array.size();i++){
                    JSONObject jboj=array.getJSONObject(i);
                    String valueByKey =    getValueByKey(jboj,parmarterKey);
                    if (valueByKey!=null){
                        return valueByKey;
                    }
                }
            } else {
                return (String) jsonObject.get(parmarterKey);
            }
        }
        return null;
    }

    @Override
    public void run() {
        System.out.println("处理json数据逻辑");
    }
}
